<?php



namespace App\Http\Controllers\Backend1;
use App\Services\Company\Models\CompanyPrivilege;
use App\Services\Company\Models\CompanyRole;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Http\Requests\Backend\CompanyRoleRequest;


class CompanyRoleController extends BaseController
{




    public function index()
    {

        $roles =   CompanyRole::query()->with(['privileges','expireds'])->get()->toArray();

        return $this->successData(compact('roles'));
    }



    public function store(CompanyRoleRequest $request,CompanyRole $role)
    {
        $data = $request->filldata();
        $role->fill($data)->save();
        $role->privileges()->createMany($data['privileges']);
        $role->expireds()->createMany($data['expireds']);
        return $this->success(__('插入版本成功'));
    }

    /**编辑
     * @param $id
     * @return JsonResponse
     */
    public function edit($id)
    {
        $role = CompanyRole::query()->with(['privileges','expireds'])->where('id',$id)->first();
        return $this->successData(compact('role'));
    }

    public function update(CompanyRoleRequest $request, $id)
    {
        $data =  $request->filldata();
        $role = CompanyRole::findOrFail($id);
        $role->fill($data)->save();
        return $this->success();
    }

    public function delete($id)
    {
        $role = CompanyRole::findOrFail($id);
        $role->delete();
        $role->privileges()->delete();
        return $this->success(__('删除成功'));
    }

    public function storePrivilege(Request $request,$id)
    {
        $data= $request->input('privileges',[]);
        $role = CompanyRole::query()->where('id',$id)->first();
        $privilege = new  CompanyPrivilege($data);
        $role->privileges()->save($privilege);

        return $this->success(__('新增权限成功'));
    }
    public  function deletePrivilege(Request $request,$id)
    {
        $privilegeId= $request->input('privilege_id');
        $role = CompanyRole::query()->where('id',$id)->first();
        $role ->privileges()->delete($privilegeId);
        return $this->success(__('删除权限成功'));

    }

    public function  updatePrivilege(Request $request,$id)
    {
        $title = $request->input('title');
        $privilege  = CompanyPrivilege::query()->where('id',$id)->first();
        $privilege->update(['title'=>$title]);
        return $this->success(__('更新成功'));

    }



}
